package com.security.filter;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @作者: 林江
 * @创建时间: 2024/1/14
 * @功能:
 */
public class CaptchaFilter extends OncePerRequestFilter {

    private AntPathRequestMatcher requiresAuthenticationRequestMatcher =
            new AntPathRequestMatcher("/login");

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (!requiresAuthentication(request, response)) {
            filterChain.doFilter(request, response);
            return;
        }
        // 进行验证码拦截
        String code = request.getParameter("code");
        if (StringUtils.isEmpty(code)) {
            throw new BadCredentialsException("验证码为空");
        }
        // 从缓存中获取验证码
        String redisCode = null;
        if (StringUtils.isEmpty(redisCode)) {
            throw new BadCredentialsException("验证码已过期");
        } else if (code.equals(redisCode)) {
            throw new BadCredentialsException("验证码错误");
        } else {
            filterChain.doFilter(request, response);
        }
    }

    /**
     * 指示此筛选器是否应尝试处理当前调用的登录请求。
     * 在与属性匹配filterProcessesUrl之前，它会从请求 URL 的“path”部分中删除任何参数
     * （例如 https://host/myapp/index.html;jsessionid=blah 中的 jsessionid 参数）。
     * 子类可能会覆盖特殊要求，例如 Tapestry 集成。
     * 返回：
     * true 筛选器是否应尝试身份验证， false 否则
     */
    protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
        if (this.requiresAuthenticationRequestMatcher.matches(request)) {
            return true;
        }
        return false;
    }
}
